import 'dart:collection';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/speak/tts_base_engine.dart';
import 'package:flutter_deer/util/toast_utils.dart';

import 'package:flutter_deer/database/beans/get_user_info_entity.dart';
import 'package:flutter_deer/net/conmmon_net_util.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';

class TtsEngineGbSpeaker extends ITtsBaseEngine {
  factory TtsEngineGbSpeaker() => _instance;

  TtsEngineGbSpeaker._internal();

  // 单例实例
  static final TtsEngineGbSpeaker _instance = TtsEngineGbSpeaker._internal();

  final reqTime = DateTime.now().millisecondsSinceEpoch;
  final memberCode = '1FF5CF34A541A4259E82E04A5988033A';
  final apiKey = '7C3581H4VD2C2BCTFGJKFV77V6SAC0NH';
  final deviceID = '00164263667139276';

  // 核心组件
  final Queue<String> _speechQueue = Queue();

  /// 初始化 TTS 引擎
  Future<void> init({
    Function(dynamic)? onError,
    Function()? onComplete,
  }) async {}

  /// 播报文本（支持队列）
  Future<void> speak(String text) async {
    _speechQueue.add(text);
    await _processQueue();
  }

  /// 处理队列中的下一个任务
  Future<void> _processQueue() async {
    if (_speechQueue.isEmpty) {
      return;
    }

    final text = _speechQueue.removeFirst();
    try {
      // await _flutterTts.speak(text);
      await CommonNetUtil.requestNetworkGbPrinter<List<GetUserInfoEntity>>(Method.post, url: HttpApi.gbPrinter_sendVoice, params: {
        'reqTime': reqTime,
        'securityCode': '$memberCode${deviceID}${reqTime}${apiKey}'.toMd5,
        'memberCode': memberCode,
        'deviceID': deviceID,
        'voice': '2004|2005|2008|2009',
      }, onSuccess: (data) {
        print(' 发送语音成功 $data');
        _processQueue();
      }, onError: (e, error) {
        Toast.show(' 佳博语音发送失败 $error');
        print(' 发送语音失败 $error');
        _processQueue();
      });
    } catch (e) {
      _processQueue();
    }
  }

  /// 设置音量 (0.0~1.0)
  Future<void> setVolume(double volume) async {}

  /// 设置语速 (0.0~1.0)
  Future<void> setSpeechRate(double rate) async {}

  /// 设置音调 (0.0~2.0)
  Future<void> setPitch(double pitch) async {}

  /// 切换语音
  Future<void> setVoice(Map<String, String> voice) async {}

  /// 停止播放
  Future<void> stop() async {}
}
